package br.com.binding.rebind.template;

import br.com.binding.rebind.ListenerTemplate;

import com.google.gwt.core.ext.typeinfo.JField;
import br.com.binding.client.bind.annotations.Bound;
import br.com.binding.client.bind.annotations.BoundProperty;

public class PropertyChangeTemplate implements ListenerTemplate {
    
  protected static String nl;
  public static synchronized PropertyChangeTemplate create(String lineSeparator)
  {
    nl = lineSeparator;
    PropertyChangeTemplate result = new PropertyChangeTemplate();
    nl = null;
    return result;
  }

  public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
  protected final String TEXT_1 = "addPropertyChangeListener(new br.com.binding.client.event.PropertyChangeListener() {" + NL + "                            public void propertyChanged(br.com.binding.client.event.PropertyChangeEvent evt) {" + NL + "                                String propertyName = evt.getPropertyName();";
  protected final String TEXT_2 = NL + "                                if(propertyName.equals(\"";
  protected final String TEXT_3 = "\")){";
  protected final String TEXT_4 = NL + "                                    ";
  protected final String TEXT_5 = ".setText((String) evt.getNewValue());" + NL + "                                    return;" + NL + "                                }";
  protected final String TEXT_6 = NL + "                            }" + NL + "                        });";

    /* (non-javadoc)
     * @see IGenerator#generate(Object)
     */
    public String generate(Object argument)
  {
    final StringBuffer stringBuffer = new StringBuffer();
    
    JField field = (JField)argument;
    Bound bind = field.getAnnotation(Bound.class);
    BoundProperty[] properties = bind.properties(); 

    stringBuffer.append(TEXT_1);
    
                                	for(BoundProperty property : properties){
                                
    stringBuffer.append(TEXT_2);
    stringBuffer.append(property.name());
    stringBuffer.append(TEXT_3);
    stringBuffer.append(TEXT_4);
    stringBuffer.append(property.viewProperty());
    stringBuffer.append(TEXT_5);
    }
    stringBuffer.append(TEXT_6);
    return stringBuffer.toString();
  }
} 